import copy
from rest_framework.views import APIView
from SearchEngines.Function import getMedicineInstructionsFromScheduler
from SecureHelperServer.settings import formatResponseData
from utils.conf import Response


class SearchRecognitionView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = []
    # 局部(本视图有效)权限类
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        输入框搜索药品
        """
        data = copy.deepcopy(formatResponseData)
        try:
            question = request.data.get("question")

            if not question:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 得到药品信息

            # 得到药品信息
            medicineInstructions = getMedicineInstructionsFromScheduler(boldText=question)

            if not medicineInstructions:
                return Response(data=data, responseMsg="未识别出药品",
                                loggerMsg=f"输入框搜索药品：未识别出药品，question={question}", isError=True)

            data["data"]["searchResult"] = {
                'name': medicineInstructions["药品名称"],
                'content': medicineInstructions
            }
            return Response(data=data, loggerMsg=f"输入框搜索药品：成功，question={question}")

        except Exception as e:
            return Response(data=data, responseMsg="未识别出药品",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
